// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Xml.Serialization;

namespace BlueOnionSoftware.Bloget
{
    public class Reference
    {
        private readonly Guid _id = Guid.NewGuid();
        private readonly string _title = string.Empty;
        private string _link = string.Empty;
        private DateTime _date = DateTime.UtcNow;

        public Reference()
        {
        }

        internal Reference(Reference reference)
        {
            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }
            _id = reference._id;
            _title = reference._title;
            _link = reference._link;
            _date = reference._date;
        }

        [XmlElement("id")]
        public Guid Id
        {
            get { return _id; }
        }

        [XmlElement("link")]
        public string Link
        {
            get { return _link; }
            set { _link = value; }
        }

        [XmlElement("date")]
        public DateTime Date
        {
            get { return _date; }
        }

        public override string ToString()
        {
            return string.Format(CultureInfo.CurrentCulture, "{0} ({1})",
                                 _date.ToString("u", CultureInfo.CurrentCulture), _link);
        }
    }

    public class ReferenceCollection : KeyedCollection<Guid, Reference>
    {
        public ReferenceCollection()
        {
        }

        internal ReferenceCollection(IEnumerable<Reference> referenceCollection)
        {
            if (referenceCollection == null)
            {
                throw new ArgumentNullException("referenceCollection");
            }
            foreach (var reference in referenceCollection)
            {
                Add(new Reference(reference));
            }
        }

        protected override Guid GetKeyForItem(Reference item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            return item.Id;
        }

        internal bool ContainsUrl(string url)
        {
            foreach (var reference in this)
            {
                if (string.Compare(reference.Link, url, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return true;
                }
            }

            return false;
        }
    }
}